package com.bootdo.order.utils;

import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bootdo.common.utils.DateUtils;

public class HttpClientUtil {

    public static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    private static CloseableHttpClient getTrust() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception e) {
            log.error("====创建https失败=====>" + e);
            log.info("====创建https失败=====>" + e);
        }
        return  HttpClients.createDefault();
    }

    /**
     * http请求post方式
     * @throws Exception
     * @method post
     * @author Xia.Zhuming
     * @date 2018年3月16日
     */
    private static String post(String url, Map<String,String> map) throws Exception{
        log.info("请求的URL为===========================>" + url);
        log.info("请求的URL参数为===========================>" + map.toString());
        //实例化httpClient
        CloseableHttpClient client = HttpClients.createDefault();
        if (url.startsWith("https")){
            client = getTrust();
        }
        //设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000 * 60 * 3).setConnectionRequestTimeout(1000 * 60 * 3).setSocketTimeout(1000 * 60 * 3).setRedirectsEnabled(true).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        List<NameValuePair> list = new ArrayList<>();
        if(map != null && !(map.keySet().isEmpty())){
            Set<String> set = map.keySet();
            for(String key : set){
                list.add(new BasicNameValuePair(key, map.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(list, StandardCharsets.UTF_8.name()));
        }
        log.info("开始请求=========>" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:SS"));
        CloseableHttpResponse response = client.execute(httpPost);
        log.info("结束请求=========>" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:SS"));
        HttpEntity entity = response.getEntity();
        String respStr = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
        log.info("返回参数为===========================>" + respStr);
        return respStr;
    }

    public static String httpPost(String url, Map<String, String> map, String sign) throws Exception{
        map.put("sign", sign);
        map.remove("token");
        return post(url,map);
    }

}
